package com.rritw.webtools.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

public class ServletUtil {

    public static final String herf(HttpServletRequest req) {
        String queryString = req.getQueryString();
        if (queryString == null) {
            @SuppressWarnings("rawtypes")
            Enumeration enu = req.getParameterNames();
            StringBuilder buff = new StringBuilder();
            String name, value;
            for (;;) {
                if (enu.hasMoreElements()) {
                    name = (String) enu.nextElement();
                    value = req.getParameter(name);
                    buff.append('&').append(name).append('=').append(value);
                } else {
                    break;
                }
            }
            if (buff.length() > 0) {
                buff.deleteCharAt(0);
                queryString = buff.toString();
            }
        }
        if (queryString == null) {
            return req.getRequestURI();
        } else {
            return new StringBuilder(req.getRequestURI()).append('?').append(queryString).toString();
        }
    }

    /**
     * 通过参数读取内容
     * 
     * @param req
     * @return
     */
    public static final String getContentFromParameter(HttpServletRequest req) {
        @SuppressWarnings("rawtypes")
        Enumeration enu = req.getParameterNames();
        StringBuilder buff = new StringBuilder();
        String name, value;
        for (;;) {
            if (enu.hasMoreElements()) {
                name = (String) enu.nextElement();
                value = req.getParameter(name);
                buff.append('&').append(name).append('=').append(value);
            } else {
                break;
            }
        }
        if (buff.length() > 0) {
            buff.deleteCharAt(0);
        }
        return buff.toString();
    }

    /**
     * 获取HttpServletRequest的Post的数据
     * 
     * @param req
     * @return
     * @throws IOException
     */
    public static final String getContentByStream(HttpServletRequest req) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        try {
            is = ServletActionContext.getRequest().getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            is.close();
            return sb.toString();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
